package platform.filenetty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import platform.common.CommonInfo;
import platform.filenetty.domain.FileTransferProtocol;
import platform.filenetty.util.MsgUtil;

import java.io.File;

public class NettyClient {

    // 配置服务端NIO线程组
    private EventLoopGroup group = new NioEventLoopGroup();
    private Channel channel;

    public static void main(String[] args) {
        //启动客户端
        ChannelFuture channelFuture = new NettyClient().connect(CommonInfo.url,CommonInfo.port);

        //文件信息{文件大于1024kb方便测试断点续传}
        File file = new File("D:\\测试传输文件.zip");
        FileTransferProtocol fileTransferProtocol = MsgUtil.buildRequestTransferFile(file.getAbsolutePath(), file.getName(), file.length());

        //发送信息；请求传输文件
        channelFuture.channel().writeAndFlush(fileTransferProtocol);

    }

    private ChannelFuture connect(String url, int port) {
        ChannelFuture future =null;
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.AUTO_READ,true);
            bootstrap.handler(new MyChannelInitializer());
             future = bootstrap.connect(url,port).syncUninterruptibly();
            System.out.println("启动成功");
            this.channel = future.channel();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != future && future.isSuccess()){
                System.out.println("启动成功");
            }else{
                System.out.println("启动失败");
            }
            group.shutdownGracefully();
        }
        return future;
    }
}
